package com.nku.mason.lucene;

import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Formatter;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.Scorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;

import com.nku.mason.lucene.entity.Article;
import com.nku.mason.lucene.util.LuceneUtil;
/**
 * 高亮就是将高亮后的文本添加至document的相应字段中
 * @author Mason
 *
 */
public class TestHighlighter {
	// 查询
	public void searchForKeyword(String keyword) throws Exception {
		List<Article> list = new ArrayList<>();
		Directory ramDirectory = new RAMDirectory(LuceneUtil.getDirectory());
		IndexSearcher indexSearcher = new IndexSearcher(ramDirectory);
		QueryParser queryParser = new QueryParser(LuceneUtil.getVersion(), "content", LuceneUtil.getAnalyzer());
		Query query = queryParser.parse(keyword);
		TopDocs topDocs = indexSearcher.search(query, 100);
		//对含有关键字的字符串高亮
		Formatter formatter = new SimpleHTMLFormatter("<font color='red'>", "</font>");
		Scorer fragmentScorer = new QueryScorer(query);
		Highlighter highlighter = new Highlighter(formatter, fragmentScorer);
		/**********************/
		for (int i = 0; i < topDocs.scoreDocs.length; i++) {
			int no = topDocs.scoreDocs[i].doc;
			//这时关键字还没有高亮
			Document document = indexSearcher.doc(no);
			//关键字高亮
			String contentHighlighted = highlighter.getBestFragment(LuceneUtil.getAnalyzer(), "content", document.get("content"));
			//将高亮后的结果再次封装到document对象中
			document.getField("content").setValue(contentHighlighted);
			
			Article article = (Article) LuceneUtil.document2JavaBean(document, Article.class);
			list.add(article);
		}
		indexSearcher.close();

		for (Article a : list) {
			System.out.println(a);
		}
	}
	
	public static void main(String[] args) throws Exception {
		TestHighlighter testHighlighter = new TestHighlighter();
		testHighlighter.searchForKeyword("南");
	}
}
